<?php
namespace app\admin\controller;

use app\common\controller\Adminbase;
use think\facade\Cache;
use app\admin\model\Bad as BadModel;

class Bad extends Adminbase
{
    public function index()
    {
        if ($this->request->isAjax()) {
            $where = [];
            $page = $this->request->param('page');
            $limit = $this->request->param('limit');
            if($this->request->param('filter')){
                $filter = $this->request->param('filter');
                $filter = json_decode($filter,true);
                foreach($filter as $k=>$row){
                    $where[] = [$k,'like','%'.trim($row).'%'];
                }
            }
            $offset = ($page - 1)*$limit;
            $result = BadModel::where('deleted',0)->where($where)->limit($offset,$limit)->select();
            $count = BadModel::where('deleted',0)->where($where)->count();
            $result = array("code" => 0, 'count'=>$count,"data" => $result);
            return json($result);
        } else {
            return $this->fetch();
        }
    }

    public function add()
    {
        return $this->fetch();
    }

    public function edit()
    {
        $id = $this->request->param('id');
        $bad = BadModel::find($id);
        $this->assign('bad',$bad);
        return $this->fetch();
    }

    public function editPost()
    {
        $data = $this->request->param();
        if(!$data['nums']){
            $this->error('请输入不良品编号');
        }
        if(!$data['title']){
            $this->error('请输入不良品名称');
        }
        if(!isset($data['id'])){
            $data['addtime'] = date('Y-m-d H:i:s');
            BadModel::insert($data);
        }else{
            $data['mdtime'] = date('Y-m-d H:i:s');
            BadModel::where('id',$data['id'])->update($data);
        }
        $this->success('添加成功');
    }

    public function delete()
    {
        $data = $this->request->param();
        BadModel::where('id',$data['id'])->update(['deleted'=>1]);
        $this->success('删除成功',url('index'));
    }
}